﻿using ProjectScheduling.daos;
using System.Data;

namespace ProjectScheduling
{
    public partial class SalesPage : UserControl
    {
        public readonly static SalesPage b = new();
        private readonly SaleDao dao = SaleDao.Base;
        public SalesPage()
        {

            InitializeComponent();
            view_all.AutoGenerateColumns = false;
            AddSalesForm.b.action_ok = Search;
        }

        private void Btn_add_Click(object sender, EventArgs e)
        {

            AddSalesForm.b.Init(0);
            AddSalesForm.b.ShowDialog();
        }
        private void Search()
        {
            view_all.DataSource = dao.ToTable("SELECT *,IIF(IsLock=1,'禁用','启用') AS StateStr FROM Saler");
        }

        private void SalesPage_Load(object sender, EventArgs e)
        {
            Search();
        }

        private void SalesPage_VisibleChanged(object sender, EventArgs e)
        {
            if (view_all.Visible) Search();
        }

        private void View_all_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;
            if (view_all.DataSource is not DataTable t) return;
            var row = t.Rows[e.RowIndex];
            var id = Convert.ToInt32(row["Id"]);
            switch (e.ColumnIndex)
            {
                // 启用/禁用
                case 5:

                    var state = Convert.ToBoolean(row["IsLock"]);
                    dao.Update(new models.Sales { Id = id, IsLock = !state }, it => new { it.IsLock });
                    Search();
                    MessageBox.Show((state ? "启用" : "禁用") + "成功", "成功提示");
                    break;
                // 编辑
                case 6:
                    AddSalesForm.b.Init(id);
                    AddSalesForm.b.ShowDialog();
                    break;
                // 删除
                case 7:
                    if (MessageBox.Show("是否确定要删除当前销售？", "删除确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        dao.Delete(id);
                        Search();
                    }
                    break;
            }
            Console.WriteLine(e.ColumnIndex);
        }

        private void View_all_SelectionChanged(object sender, EventArgs e)
        {
            view_all.ClearSelection();
        }
    }
}
